package com.system.xingzhi.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.system.xingzhi.controller.*.*(..))")
    public void log(){
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "," + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request:{}", requestLog);
        logger.info("-------------------------doBefore---------------------");
    }

    @After("log()")
    public void doAfter() {
        logger.info("----------------------doAfter-----------------------");
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterReturn(Object result) {
        logger.info("Result : " + result);
    }

    @Around("log()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint){
        long current = System.currentTimeMillis();
        Object proceed = null;
        try{
            proceed = proceedingJoinPoint.proceed();
        }catch (Throwable throwable){
            throwable.printStackTrace();
        }
        long end = System.currentTimeMillis();
        logger.info("程序运行时间："+(current-end));
        return proceed;
    }

    private class RequestLog {
        private String Url;
        private String ip;
        private String classMethod;
        private Object arg[];

        public RequestLog(String url, String ip, String classMethod, Object[] arg) {
            Url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.arg = arg;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "Url='" + Url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", arg=" + Arrays.toString(arg) +
                    '}';
        }
    }
}
